package org.nood.iptv.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.nood.iptv.R;
import org.nood.iptv.adapter.ProgramListAdapter;
import org.nood.iptv.entity.ProgramResult;
import org.nood.iptv.utils.Contants;
import org.nood.iptv.utils.DateUtils;
import org.nood.iptv.utils.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Noodlewar
 * @date 2017/11/28
 */
public class ProgramScheduleFragment extends Fragment {

    private Context context;

    @BindView(R.id.program_view)
    ListView program_view;
    @BindView(R.id.program_no_list)
    View program_no_list;
    @BindView(R.id.program_loading)
    View program_loading;

    private ProgramListAdapter programeListAdapter;

    private List<ProgramResult> programLists;

    public static ProgramScheduleFragment newInstance(String channelId, int position) {
        Bundle args = new Bundle();
        args.putString("channelId", channelId);
        args.putInt("position", position);
        ProgramScheduleFragment fragment = new ProgramScheduleFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.program_pager, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        String channelId = getArguments().getString("channelId");
        int position = getArguments().getInt("position");

        this.context = view.getContext();
        initData(channelId, position);
    }

    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            ProgramResult programResult = programLists.get(position);
            int status = programResult.getStatus();
            if (status == -1) {
                listener.onScheduleSelected(programResult.getPlayseekURL());
            } else if (status == 1) {
                listener.onScheduleSelected(null);
            } else {
                Toast.makeText(context, "未播出", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (programLists != null && programLists.size() > 0) {
                //有数据
                //设置适配器
                programeListAdapter = new ProgramListAdapter(context, programLists);
                program_view.setOnItemClickListener(new MyOnItemClickListener());
                program_view.setAdapter(programeListAdapter);
                program_no_list.setVisibility(View.GONE);
            } else {
                //没有数据
                //文本显示
                program_no_list.setVisibility(View.VISIBLE);
            }
            //ProgressBar隐藏
            program_loading.setVisibility(View.GONE);
        }
    };

    public void initData(String channelId, int position) {
        LogUtils.e("节目表数据初始化");
        String positionDate = DateUtils.getPositionDate(position);
        getDataGetByOkhttpUtils(channelId, positionDate);
    }

    /**
     * 使用okhttp-utils的get请求网络文本数据
     */
    public void getDataGetByOkhttpUtils(String channelId, String positionDate) {
        String url = Contants.BASE_URL + "client/channel/" + channelId + "/" + positionDate;
        LogUtils.e(url);
        OkGo.<String>get(url).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String data = response.body();
                if (data != null && !"".equals(data)) {
                    JSONObject object = JSON.parseObject(data);
                    programLists = JSON.parseArray(object.getString("scheduleList"), ProgramResult.class);
                    handler.sendEmptyMessage(10);
                }
            }
        });
    }

    private OnScheduleSelectedListener listener;

    public interface OnScheduleSelectedListener {
        /**
         * 节目单点击事件
         *
         * @param url
         */
        void onScheduleSelected(String url);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            listener = (OnScheduleSelectedListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + "must implement OnScheduleSelectedListener");
        }
    }

}
